<template>
	<view class='sign-contents'>
		<!-- 横屏 -->
		<view class="draw-inner landscape" v-show="direction == 'landscape'">
			<canvas class='canvasArea' :ref="`canvasArea${direction}`" :canvas-id="`canvasArea${direction}${direction == 'landscape'?'':'hide'}`"
				@touchmove='move' @touchstart='start($event)' @touchend='end' @touchcancel='cancel' @longtap='tap'
				disable-scroll='true' @error='error' :style="canvasStyleW">
			</canvas>
			<view class="actions-wraper" :style="{padding: osType().isTablet?0: '0 150rpx' }">
				<view class="close btn" @tap="close">
					<text>关闭</text>
				</view>
				<view class="over btn" @tap='clearClick'>
					<text>重写</text>

				</view>
				<view class="resign btn" @tap="overSign">
					<text>保存</text>
				</view>
			</view>
		</view>
		<!-- 竖屏 -->
		<view class="draw-inner portrait" v-show="direction == 'portrait'">
			<view class="actions-wraper" :style="{padding: osType().isTablet?0: '150rpx 0' }">
				<view class="close btn rotate" @tap="close">
					<text>关闭</text>
				</view>
				<view class="over btn rotate" @tap='clearClick'>
					<text>重写</text>

				</view>
				<view class="resign btn rotate" @tap="overSign">
					<text>保存</text>
				</view>
			</view>
			<canvas class='canvasArea' :ref="`canvasArea${direction}`" :canvas-id="`canvasArea${direction}${direction == 'portrait'?'':'hide'}`"
				@touchmove='move' @touchstart='start($event)' @touchend='end' @touchcancel='cancel' @longtap='tap'
				disable-scroll='true' @error='error' :style="canvasStyleH">
			</canvas>
		</view>
	</view>
</template>

<script>
	export default {
		props: {

		},
		data() {
			return {
				isEnd: false, // 是否签名
				content: null, // 画布对象
				isLandScape: false,
				initnum: 0,
				touchs: [], // 需要绘画的点
				direction: 'portrait', // 屏幕方向landscape： 横屏 portrait：竖屏
				canvasStyleH: { // 竖屏样式
					width: (parseInt(document.body.clientWidth) - 85) + 'px', // 画布的宽度= 文档高度减去按钮区域的高度
					height: (parseInt(document.body.clientHeight) - 85) + 'px', //画布的高度 = 文档高度减去按钮区域的高度
				},
				canvasStyleW: { // 横屏样式
					width: (parseInt(document.body.clientWidth) - 85) + 'px', //画布的高度 = 文档高度减去按钮区域的高度
					height: (parseInt(document.body.clientHeight) - 85) + 'px', // 画布的宽度= 文档高度减去按钮区域的高度
				}

			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		created(options) {
			this.init();
			uni.onWindowResize((res) => {
				this.handScreenDirectionChange(res);
			})

		},
		onResize() {
			uni.getSystemInfo({
				success: (res) => {
					if (res.windowWidth > res.windowHeight) {
						// 横屏
						this.isLandScape = true
					} else {
						// 竖屏
						this.isLandScape = false
					}
				}
			})
		},
		methods: {
			init() {
				this.handScreenDirectionChange({
					noDeedToinit: true
				}); // noDeedToinit不需要再次init
				//获得Canvas的上下文
				this.content = uni.createCanvasContext(`canvasArea${this.direction}`)
				console.log('创建时===this.initnum===', this.initnum);
				console.log('创建时===this.canvasID===', `canvasArea${this.direction}`);
				//设置线的颜色
				this.content.setStrokeStyle("#000")
				//设置线的宽度
				this.content.setLineWidth(5)
				//设置线两端端点样式更加圆润
				this.content.setLineCap('round')
				//设置两条线连接处更加圆润
				this.content.setLineJoin('round')
			},
			resetWH() { // 重置画布宽高
				this.canvasStyleH.width = (parseInt(document.body.clientWidth) - 85) + 'px'; // 画布的宽度= 文档高度减去按钮区域的高度 竖屏样式
				this.canvasStyleH.height = (parseInt(document.body.clientHeight) - 85) + 'px'; //画布的高度 = 文档高度减去按钮区域的高度
				// 横屏样式
				this.canvasStyleW.width = (parseInt(document.body.clientWidth) - 85) + 'px'; //画布的高度 = 文档高度减去按钮区域的高度
				this.canvasStyleW.height = (parseInt(document.body.clientHeight) - 85) + 'px'; // 画布的宽度= 文档高度减去按钮区域的高度
			},
			handScreenDirectionChange({
				noDeedToinit
			} = params) {
				this.clearClick();
				this.resetWH(); // 重新获取屏幕宽高
				if (document.body.clientWidth > document.body.clientHeight) { // 宽大于高时 横屏
					this.direction = 'landscape'
				} else { // 竖屏

					this.direction = 'portrait'
				}
				if (noDeedToinit) return; // 不需要再次init
				this.content = null;
				this.initnum++;
				this.$nextTick(() => {
					this.init();
				})

			},
			overSign() { // 签名结束
				if (this.isEnd) {
					uni.canvasToTempFilePath({
						canvasId: `canvasArea${this.direction}`,
						quality: 1,
						success: async (res) => {
							console.log('res=====', res);
							//设置图片
							let imgData = '';
							if (this.direction == 'portrait') {
								imgData = await this.rotateBase64Img(res.tempFilePath, -90);
							} else {
								imgData = res.tempFilePath;
							}

							this.$emit('signEnd', {
								base64Img: imgData
							});
						}
					})

				} else {
					uni.showToast({
						title: '请先完成签名',
						icon: "none",
						duration: 1500,
						mask: true
					})
				}
			},
			close() {
				this.$emit('close')
			},

			// 画布的触摸移动开始手势响应
			start(event) {
				// console.log(event)
				//获取触摸开始的 x,y
				let point = {
					x: event.changedTouches[0].x,
					y: event.changedTouches[0].y
				}
				// console.log(point)
				this.touchs.push(point);

			},
			// 画布的触摸移动手势响应
			move(e) {
				let point = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				// console.log(point)
				this.touchs.push(point)
				if (this.touchs.length >= 2) {
					this.draw(this.touchs)
				}
			},

			// 画布的触摸移动结束手势响应
			end(e) {
				// 设置为已经签名
				this.isEnd = true;
				if (this.touchs.length == 1) {
					console.log('this.touchs=========', JSON.stringify(this.touchs));
					this.touchs[1] = {
						x: this.touchs[0].x + 2,
						y: this.touchs[0].y
					};
					this.draw(this.touchs)
				}
				// 清空轨迹数组
				for (let i = 0; i < this.touchs.length; i++) {
					this.touchs.pop()
				}

			},

			// 画布的触摸取消响应
			cancel(e) {
				console.log("触摸取消" + e)
			},

			// 画布的长按手势响应
			tap(e) {},

			error(e) {
				console.log("画布触摸错误" + e)
			},

			//绘制
			draw(touchs) {
				let point1 = touchs[0]
				let point2 = touchs[1]
				touchs.shift()
				this.content.moveTo(point1.x, point1.y)
				this.content.lineTo(point2.x, point2.y)
				this.content.lineWidth = 6;
				this.content.stroke()
				this.content.draw(true)
			},
			//清除操作
			clearClick() {
				// 设置为未签名
				if (!this.content) return;
				this.isEnd = false;
				let curCanvasStyle = this.direction == 'landscape' ? this.canvasStyleW : this.canvasStyleH;
				let clearW = parseInt(curCanvasStyle.width);
				let clearH = parseInt(curCanvasStyle.height);
				console.log(clearW, clearH);
				//清除画布
				this.content.clearRect(0, 0, clearW, clearH)
				this.content.draw(true)
			},
			//src - 图片路径，deg旋转角度
			async rotateBase64Img(src, edg) {
				return new Promise((resolve, reject) => {
					var canvas = document.createElement("canvas");
					var ctx = canvas.getContext("2d");
					var imgW; //图片宽度
					var imgH; //图片高度
					var size; //canvas初始大小
					if (edg % 90 != 0) {
						console.error("旋转角度必须是90的倍数!");
						throw '旋转角度必须是90的倍数!';
					}
					(edg < 0) && (edg = (edg % 360) + 360)
					const quadrant = (edg / 90) % 4; //旋转象限
					const cutCoor = {
						sx: 0,
						sy: 0,
						ex: 0,
						ey: 0
					}; //裁剪坐标
					var image = new Image();
					image.crossOrigin = "anonymous"
					image.src = src;
					image.onload = () => {
						imgW = image.width;
						imgH = image.height;
						size = imgW > imgH ? imgW : imgH;
						canvas.width = size * 2;
						canvas.height = size * 2;
						switch (quadrant) {
							case 0:
								cutCoor.sx = size;
								cutCoor.sy = size;
								cutCoor.ex = size + imgW;
								cutCoor.ey = size + imgH;
								break;
							case 1:
								cutCoor.sx = size - imgH;
								cutCoor.sy = size;
								cutCoor.ex = size;
								cutCoor.ey = size + imgW;
								break;
							case 2:
								cutCoor.sx = size - imgW;
								cutCoor.sy = size - imgH;
								cutCoor.ex = size;
								cutCoor.ey = size;
								break;
							case 3:
								cutCoor.sx = size;
								cutCoor.sy = size - imgW;
								cutCoor.ex = size + imgH;
								cutCoor.ey = size + imgW;
								break;
						}
						ctx.translate(size, size);
						ctx.rotate(edg * Math.PI / 180);
						ctx.drawImage(image, 0, 0);
						var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
						if (quadrant % 2 == 0) {
							canvas.width = imgW;
							canvas.height = imgH;
						} else {
							canvas.width = imgH;
							canvas.height = imgW;
						}
						ctx.putImageData(imgData, 0, 0);
						resolve(canvas.toDataURL())
					};
				})
			},
			/**
			 *  @description  判断运行的平台是ios手机、还是平板还是电脑
			 * @return {Object}  返回判断类型后的机型参数：isTablet：是否是平板，isIPhone是否是苹果手机，isAndroid是否是安卓手机，isPhone是否是手机平台，isPc： 是否是pc
			 */
			osType() {
				var ua = navigator.userAgent,
					isWindowsPhone = /(?:Windows Phone)/.test(ua),
					isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
					isAndroid = /(?:Android)/.test(ua),
					isFireFox = /(?:Firefox)/.test(ua),
					isChrome = /(?:Chrome|CriOS)/.test(ua),
					isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox &&
						/(?:Tablet)/.test(ua)),
					isIPhone = /(?:iPhone)/.test(ua) && !isTablet,
					isPc = !isIPhone && !isAndroid && !isSymbian;
				return {
					isTablet: isTablet,
					isIPhone: isIPhone,
					isAndroid: isAndroid,
					isPhone: isIPhone || isAndroid,
					isPc: isPc
				};
			},

		},


	}
</script>

<style lang="scss" scoped>
	.canvasArea {
		margin: 10rpx;
		border: 1px solid rgba(222, 37, 37, .1);
		border-radius: 8rpx;
		background-color: #fcfcfc;
	}

	.draw-inner.portrait {
		// 竖屏
		height: 100%;
		display: flex;
		align-items: center;
	}

	.draw-inner.landscape {
		// 横屏
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		justify-content: center;
	}

	.sign-contents {
		height: 100%;
		box-sizing: border-box;
		background: white;
	}

	.actions-wraper {
		display: flex;
		align-items: center;
		justify-content: space-evenly;

		.btn {
			display: flex;
			justify-content: center;
			align-items: center;
			color: #FFFFFF;
			width: 220rpx;
			border-radius: 40rpx;

			&:active {
				background-color: #CCCCCC;
				color: #333333;
			}
		}

		.resign {
			background-color: rgb(222, 37, 37);
		}

		.over {
			color: #1A91FF;
			border: 1px solid rgba(66, 140, 244, .6);
			background-color: #fcfcfc;
		}

		.close {
			color: #666;
			border: 1px solid rgba(0, 0, 0, .1);
		}
	}

	.portrait {

		// 竖屏模式
		.actions-wraper {
			width: 120rpx;
			height: 100%;
			flex-direction: column;

			.btn {
				padding: 20rpx 20rpx;
				margin: 20rpx 0;
				font-size: 26rpx;
			}
		}
	}

	.landscape {

		// 横屏
		.actions-wraper {
			width: 100%;
			height: 50px;
			margin-top: 0px;

			.btn {
				padding: 8rpx 20rpx;
				margin: 0 20rpx;
				font-size: 16px;
			}
		}

	}


	.rotate {
		transform: rotate(90deg);
	}
</style>